package person.bangbang.im.Androidgin.Framework;

import java.util.ArrayList;
import java.util.List;
/**
 * 
 * corresponding to pidgin's accounts [subsystem].
 * 
 * @author bangbang.song@gmail.com
 */
public class Accounts {
	private List<Account> mList = new ArrayList<Account>();
	private List<OnAccountsEvent> mAccEventListener = new ArrayList<OnAccountsEvent>();
	
	public Account createAccount(String protocolId, String userName, String passward, StatusType type) {
		Account acc = null;
		if (null != findAccount(protocolId, userName)) {
			return acc;
		}
		acc = new Account(protocolId, userName, passward, type);
		add(acc);
		
		return acc;
	}
	
	public void add(Account acc) {
		mList.add(acc);
		
		doAccountAdd(acc);
	}
	public void rem(Account acc) {
		mList.remove(acc);
		
		doAccountRem(acc);
	}
	public Account findAccount(String protocolId, String userName) {
		for ( Account acc : mList) {
			if (protocolId.equals(acc.getProtocolID()) &&
				userName.equals(acc.getUserName())) {
				
				return acc;
			}
		}
		
		return null;
	}
	public List<Account> getAll(boolean isActive) {
		return mList;
	}
	public void regOnAccountEventListener(OnAccountsEvent l) {
		mAccEventListener.add(l);
	}
	public void unRegOnAccountEventListener(OnAccountsEvent l) {
		mAccEventListener.remove(l);
	}
	protected void doAccountAdd(Account acc) {
		for (OnAccountsEvent e : mAccEventListener) {
			e.onAccountAdd(acc);
		}
	}
	protected void doAccountRem(Account acc) {
		for (OnAccountsEvent e : mAccEventListener) {
			e.onAccountRem(acc);
		}
	}
	
	private Accounts(){
	}
	/**
	 * do initialization, e.g loads saved accounts.
	 */
	private void init(){
		
	}
	private void uninit(){
		
	}
	private static Accounts _instance;
	public static Accounts getInstance() {
		if (null == _instance) {
			_instance = new Accounts();
			_instance.init();
		}
		
		return  _instance;
	}
	
	
	/**
	 * 
	 * more see pidgin'docs. (sec account signal)
	 *
	 */
	public interface OnAccountsEvent {
		/**
		 * u can guess
		 * @param acc
		 */
		public void onAccountAdd(Account acc);
		/**
		 * u can guess
		 * @param acc
		 */
		public void onAccountRem(Account acc);
	}
}
